package com.demon.androidbasic.view

import android.content.Context
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2019/08/18
 * desc   : 智能显示的 TextView
 */
class SmartTextView @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = android.R.attr.textViewStyle
) : AppCompatTextView(
    context!!, attrs, defStyleAttr
), TextWatcher {
    /**
     * [TextWatcher]
     */
    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
    override fun afterTextChanged(s: Editable?) {
        // 判断当前有没有设置文本达到自动隐藏和显示的效果
        if (TextUtils.isEmpty(text.toString())) {
            if (visibility != GONE) {
                visibility = GONE
            }
        } else {
            if (visibility != VISIBLE) {
                visibility = VISIBLE
            }
        }
    }

    init {
        addTextChangedListener(this)
        // 触发一次监听
        afterTextChanged(null)
    }
}